package com.coocaa.ops.common.tool.base;

import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;

/**
 * @author bijiahao
 * @date : 2017/10/18.
 * @description 模块渲染工具类
 *
 */
@Slf4j
public class TemplateGenerUtil {
    private static VelocityEngine ve;
    private static Properties properties;
    private final static String CONTENT_ENCODING = "UTF-8";

    static {
        try {
            properties = new Properties();
            properties.setProperty(Velocity.RESOURCE_LOADER, "class");
            properties.setProperty("class.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            //关闭日志
//          Velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogChute")
            properties.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
            properties.put("runtime.log.logsystem.log4j.category", "velocity");
            properties.put("runtime.log.logsystem.log4j.logger", "velocity");
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init(properties);
            ve = velocityEngine;
        } catch (Exception e) {
            log.error("ve 初始化异常", e);
        }
    }

    public static String getResult(VelocityContext context, String templateName) {
        Template template = ve.getTemplate(templateName, CONTENT_ENCODING);
        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        sw.flush();
        try {
            sw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    public static void main(String[] args) {
        VelocityContext context = new VelocityContext();
        context.put("id", "123");
        String res = TemplateGenerUtil.getResult(context, "/onclick/video.vm");
        System.out.println(res);
    }

}
